package com.des1gn.ymgetil.service.impl;

import cn.hutool.core.text.UnicodeUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.des1gn.ymgetil.enums.ApiEnums;
import com.des1gn.ymgetil.model.*;
import com.des1gn.ymgetil.service.ProxyService;
import com.des1gn.ymgetil.service.SmallTypeService;
import com.des1gn.ymgetil.service.UserInfoService;
import com.des1gn.ymgetil.util.AesUtil;
import com.des1gn.ymgetil.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.Proxy;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;

@Service
@Slf4j
public class SmallTypeServiceImpl implements SmallTypeService {

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    ProxyService proxyService;

    @Override
    public List<SmallType> getSmallTypes(String sessionId, String productCode) {
        String url = ApiEnums.getApi("获取小类型");
        url = url.replaceAll("CODE",productCode);
        JSONObject httpResult = HttpUtil.getOkHttp(url, sessionId,null);
        if (httpResult == null || httpResult.getInteger("status") != 200){
            return null;
        }
        List<SmallType> result = new LinkedList<>();
        JSONArray list = httpResult.getJSONArray("list");
        for (Object data : list){
            result.add(JSONObject.parseObject(JSONObject.toJSONString(data),SmallType.class));
        }
        return result;
    }

    @Override
    public List<Hospital> getHospitals(String sessionId, String smallCode) {
        String url = ApiEnums.getApi("获取医院列表");
        url = url.replaceAll("SMALLCODE",smallCode);
        JSONObject httpResult = HttpUtil.getOkHttp(url, sessionId,null);
        if (httpResult == null){
            return null;
        }
        List<Hospital> result = new LinkedList<>();
        JSONArray list = httpResult.getJSONArray("list");
        for (Object data : list){
            result.add(JSONObject.parseObject(JSONObject.toJSONString(data),Hospital.class));
        }
        return result;
    }

    @Override
    public List<Product> getProducts(String sessionId, String hospitalId) {
        String url = ApiEnums.getApi("获取产品列表");
        url = url.replaceAll("HOSPITALID",hospitalId);
        JSONObject httpResult = HttpUtil.getOkHttp(url, sessionId,null);
        if (httpResult == null){
            return null;
        }
        List<Product> result = new LinkedList<>();
        JSONArray list = httpResult.getJSONArray("list");
        for (Object data : list){
            result.add(JSONObject.parseObject(JSONObject.toJSONString(data),Product.class));
        }
        return result;
    }


    @Override
    public List<DateDetail> getDateDetails(String sessionId, String productId, String hospitalId, String month) {
        List<DateDetail> result = new LinkedList<>();
        int i = 0;
        do{
            i ++;
            try {
                String url = ApiEnums.getApi("获取预约日期");
                url = url.replaceAll("PRODUCTCODE",productId);
                url = url.replaceAll("HOSPITALCODE",hospitalId);
                url = url.replaceAll("MONTH",month);
                Proxy randomProxy = proxyService.getRandomProxy();
                JSONObject httpResult = HttpUtil.getOkHttp(url, sessionId,randomProxy);
                if (httpResult == null ){
                    continue;
                }
                JSONArray list = httpResult.getJSONArray("list");
                if (!CollectionUtils.isEmpty(list)) {
                    for (Object data : list) {
                        result.add(JSONObject.parseObject(JSONObject.toJSONString(data), DateDetail.class));
                    }
                }
            }catch (Exception e){
                log.error("获取日期失败",e);
            }
        }while (CollectionUtils.isEmpty(result) && i < 3);
        return result;
    }

    @Override
    public List<TimeDetail> getTimeDetails(String sessionId, String productId, String hospitalId, String date,String key) {
        List<TimeDetail> result = new LinkedList<>();
       /* int i = 0;
        do {
            i++;
            try {
                String url = ApiEnums.getApi("获取预约时间");
                url = url.replaceAll("PRODUCTCODE", productId);
                url = url.replaceAll("HOSPITALCODE", hospitalId);
                url = url.replaceAll("DATE", date);
                Proxy randomProxy = proxyService.getRandomProxy();
                String httpResult = HttpUtil.getOkHttpStr(url, sessionId,randomProxy);
                if (httpResult == null) {
                    continue;
                }
                String realHttpResult = AesUtil.decoderAes(httpResult, sessionId, key);
                if (realHttpResult == null) {
                    continue;
                }
                JSONObject httpResultJson = JSONObject.parseObject(realHttpResult);
                JSONArray list = httpResultJson.getJSONArray("list");
                if (!CollectionUtils.isEmpty(list)) {
                    for (Object data : list) {
                        result.add(JSONObject.parseObject(JSONObject.toJSONString(data), TimeDetail.class));
                    }
                }
            }catch (Exception e){
                log.error("获取时间失败，{}",e);
            }
        }while (CollectionUtils.isEmpty(result) && i<3);*/
            String url = ApiEnums.getApi("获取预约时间");
            url = url.replaceAll("PRODUCTCODE", productId);
            url = url.replaceAll("HOSPITALCODE", hospitalId);
            url = url.replaceAll("DATE", date);
            Proxy randomProxy = proxyService.getRandomProxy();
            String httpResult = HttpUtil.getOkHttpStr(url, sessionId,randomProxy);
            if (httpResult == null) {
                return result;
            }
            String realHttpResult = AesUtil.decoderAes(httpResult, sessionId, key);
            if (realHttpResult == null) {
                return result;
            }
            JSONObject httpResultJson = JSONObject.parseObject(realHttpResult);
            JSONArray list = httpResultJson.getJSONArray("list");
            if (!CollectionUtils.isEmpty(list)) {
                for (Object data : list) {
                    result.add(JSONObject.parseObject(JSONObject.toJSONString(data), TimeDetail.class));
                }
            }
        return result;
    }

    @Override
    public String getCaptcha(String sessionId, String mxid) {
        String cookie = null;
        int i = 0;
        do {
            i++;
            try {
                String url = ApiEnums.getApi("验证是否可预约");
                url = url.replaceAll("MXID",mxid);
                JSONObject httpResult = HttpUtil.getOkHttp(url, sessionId,null);
                if (httpResult == null || httpResult.getInteger("status") != 200){
                    continue;
                }
                cookie = httpResult.getString("cookie");
            }catch (Exception e){
                log.error("获取下单资格失败，{}",e);
            }
        }while (StringUtils.isEmpty(cookie) && i<3);
        return cookie;
    }

    @Override
    public String submitOrder(String sessionId, String mxid, String productId,String date,UserInfoModel userInfo){
        String cookie = null;
        int i = 0;
        do {
            i++;
            try {
                String url = ApiEnums.getApi("提交预约");
                url = url.replaceAll("BIRTHDAY",userInfo.getBirthday());
                url = url.replaceAll("PHONE",userInfo.getTel());
                try {
                    url = url.replaceAll("USERNAME", URLEncoder.encode(userInfo.getCname(),"UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                url = url.replaceAll("SEX",userInfo.getSex());
                url = url.replaceAll("CARDNO",userInfo.getIdcard());
                url = url.replaceAll("CARDTYPE",userInfo.getDoctype());
                url = url.replaceAll("PRODUCTCODE",productId);
                url = url.replaceAll("DATE",date);
                url = url.replaceAll("MXID",mxid);
                JSONObject httpResult = HttpUtil.getOkHttp(url, sessionId,null);
                if (httpResult == null || httpResult.getInteger("status") != 200){
                    continue;
                }
                if (httpResult.getString("msg").equals("提交成功")){
                    cookie = httpResult.getString("cookie");
                }
            }catch (Exception e){
                log.error("下单失败，{}",e);
            }
        }while (StringUtils.isEmpty(cookie) && i <3);
        return cookie;
    }

    @Override
    public List<OrderInfo> getOrderList(String sessionId) {
        String url = ApiEnums.getApi("查询订单列表");
        Proxy randomProxy = proxyService.getRandomProxy();
        JSONObject httpResult = HttpUtil.getOkHttp(url, sessionId,randomProxy);
        if (httpResult == null || httpResult.getInteger("status") != 200){
            return null;
        }
        JSONArray list = httpResult.getJSONArray("list");
        List<OrderInfo> result = new LinkedList<>();
        for (Object i :  list){
            OrderInfo orderInfo = JSONObject.parseObject(JSONObject.toJSONString(i), OrderInfo.class);
            result.add(orderInfo);
        }
        return result;
    }

    @Override
    public JSONObject getOrderStatus(String sessionId) {
        JSONObject result = new JSONObject();
        String url = ApiEnums.getApi("获取订单状态");
        JSONObject httpResult = HttpUtil.getOkHttp(url, sessionId,null);
        if (httpResult == null || httpResult.getInteger("status") != 200){
            result.put("msg",httpResult.getString("msg"));
            return result;
        }
        String cookie = httpResult.getString("cookie");
        if (!StringUtils.isEmpty(cookie)) {
            result.put("cookie", cookie);
        }
        result.put("Fnumber", httpResult.getString("Fnumber"));
        return result;
    }
}


